package com.bangcommunity.bbframe.common.utils.lang;

import com.bangcommunity.bbframe.common.base.BaseMap;
import com.bangcommunity.bbframe.common.enums.BaseEnum;
import com.bangcommunity.bbframe.common.enums.BaseNumEnum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * enum相关工具
 * 
 * @author tanghc
 */
public class EnumUtils {
    /**
     * 将枚举的name批量转成枚举对象列表
     */
    public static <E extends Enum<E>> List<E> fromNames(List<String> names, Class<E> clazz) {
        List<E> list = null;
        if (null != names) {
            list = new ArrayList<>();
            for (String n : names) {
                E e = Enum.valueOf(clazz, n);
                if (null != e) {
                    list.add(e);
                }
            }
        }
        return list;
    }

    public static <E extends Enum<E>> E fromName(String name, Class<E> clazz) {
        return Enum.valueOf(clazz, name);
    }

    public static <E extends Enum<E>> E fromNameSafe(String name, Class<E> clazz) {
        try {
            return Enum.valueOf(clazz, name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 枚举对象列表批量转成name列表
     */
    public static <E extends Enum<E>> List<String> toNames(List<E> statuses) {
        List<String> names = null;
        if (null != statuses) {
            names = new ArrayList<>();
            for (E e : statuses) {
                names.add(e.name());
            }
        }
        return names;
    }

    public static <E extends Enum<E>> List<String> toNames(E... statuses) {
        if (null != statuses) {
            return toNames(Arrays.asList(statuses));
        }
        return null;
    }

    public static <E extends Enum<E> & BaseEnum> List<BaseMap<String, String>> fromEnumToStringMap(E[] es) {
        List<BaseMap<String, String>> maps = new ArrayList<>();
        if (null != es) {
            for (E e : es) {
                if (null != e && null != e.getKey()) {
                    BaseMap<String, String> map = new BaseMap(e.name(), e.getKey());
                    maps.add(map);
                }
            }
        }
        return maps;
    }

    public static <E extends Enum<E> & BaseNumEnum> List<BaseMap<Integer, String>> fromEnumToMap(E[] es) {
        List<BaseMap<Integer, String>> maps = new ArrayList<>();
        if (null != es) {
            for (E e : es) {
                if (null != e && null != e.getKey()) {
                    BaseMap<Integer, String> map = new BaseMap(e.getNum(), e.getKey());
                    maps.add(map);
                }
            }
        }
        return maps;
    }

    public static List<BaseMap<Integer, String>> fromMapToMapBean(Map<Integer, String> map) {
        List<BaseMap<Integer, String>> maps = new ArrayList<>();
        if (null != map) {
            for (Map.Entry<Integer, String> e : map.entrySet()) {
                if (null != e && null != e.getKey()) {
                    BaseMap<Integer, String> mapbean = new BaseMap(e.getKey(), e.getValue());
                    maps.add(mapbean);
                }
            }
        }
        return maps;
    }

    public static <E extends Enum<E> & BaseNumEnum> LinkedHashMap<Integer, String> fromEnumToLinkedMap(E[] es) {
        LinkedHashMap<Integer, String> maps = new LinkedHashMap<>();
        if (null != es) {
            for (E e : es) {
                if (null != e && null != e.getKey()) {
                    maps.put(e.getNum(), e.getKey());
                }
            }
        }
        return maps;
    }

    public static <E extends Enum<E> & BaseNumEnum> LinkedHashMap<Integer, BaseMap<Integer, String>> fromEnumToLinkedBaseMap(
            E[] es) {
        LinkedHashMap<Integer, BaseMap<Integer, String>> maps = new LinkedHashMap<>();
        if (null != es) {
            for (E e : es) {
                if (null != e && null != e.getKey()) {
                    maps.put(e.getNum(), new BaseMap<>(e.getNum(), e.getKey()));
                }
            }
        }
        return maps;
    }

    public static <E extends Enum<E> & BaseNumEnum> E fromNum(E[] es, Integer num) {
        if (null == num) {
            return null;
        }
        if (null != es) {
            for (E e : es) {
                if (null != e && e.getNum() == num) {
                    return e;
                }
            }
        }
        return null;
    }

    public static <E extends Enum<E> & BaseEnum> E fromEnumKey(E[] es, String key) {
        if (null == key) {
            return null;
        }
        if (null != es) {
            for (E e : es) {
                if (null != e && e.getKey().equals(key)) {
                    return e;
                }
            }
        }
        return null;
    }

    public static <E extends Enum<E> & BaseNumEnum> BaseMap<Integer, String> fromNumToBaseMap(E[] es, Integer num) {
        if (null == num) {
            return null;
        }
        if (null != es) {
            for (E e : es) {
                if (null != e && e.getNum() == num) {
                    return new BaseMap(e.getNum(), e.getKey());
                }
            }
        }
        return null;
    }

    private static final String NULL_ELEMENTS_NOT_PERMITTED = "null elements not permitted";
    private static final String CANNOT_STORE_S_S_VALUES_IN_S_BITS = "Cannot store %s %s values in %s bits";
    private static final String S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE = "%s does not seem to be an Enum type";
    private static final String ENUM_CLASS_MUST_BE_DEFINED = "EnumClass must be defined.";

    /**
     * This constructor is public to permit tools that require a JavaBean instance to operate.
     */
    public EnumUtils() {
    }

    /**
     * <p>
     * Gets the {@code Map} of enums by name.
     * </p>
     *
     * <p>
     * This method is useful when you need a map of enums by name.
     * </p>
     *
     * @param <E>
     *            the type of the enumeration
     * @param enumClass
     *            the class of the enum to query, not null
     * @return the modifiable map of enum names to enums, never null
     */
    public static <E extends Enum<E>> Map<String, E> getEnumMap(final Class<E> enumClass) {
        final Map<String, E> map = new LinkedHashMap<String, E>();
        for (final E e : enumClass.getEnumConstants()) {
            map.put(e.name(), e);
        }
        return map;
    }

    /**
     * <p>
     * Gets the {@code List} of enums.
     * </p>
     *
     * <p>
     * This method is useful when you need a list of enums rather than an array.
     * </p>
     *
     * @param <E>
     *            the type of the enumeration
     * @param enumClass
     *            the class of the enum to query, not null
     * @return the modifiable list of enums, never null
     */
    public static <E extends Enum<E>> List<E> getEnumList(final Class<E> enumClass) {
        return new ArrayList<E>(Arrays.asList(enumClass.getEnumConstants()));
    }

    /**
     * <p>
     * Gets the {@code List} of enums.
     * </p>
     *
     * <p>
     * This method is useful when you need a list of enums rather than an array.
     * </p>
     *
     * @param <E>
     *            the type of the enumeration
     * @param enumClass
     *            the class of the enum to query, not null
     * @return the modifiable list of enums, never null
     */
    public static List getEnums(final Class enumClass) {
        return new ArrayList(Arrays.asList(enumClass.getEnumConstants()));
    }

    /**
     * <p>
     * Checks if the specified name is a valid enum for the class.
     * </p>
     *
     * <p>
     * This method differs from {@link Enum#valueOf} in that checks if the name is a valid enum
     * without needing to catch the exception.
     * </p>
     *
     * @param <E>
     *            the type of the enumeration
     * @param enumClass
     *            the class of the enum to query, not null
     * @param enumName
     *            the enum name, null returns false
     * @return true if the enum name is valid, otherwise false
     */
    public static <E extends Enum<E>> boolean isValidEnum(final Class<E> enumClass, final String enumName) {
        if (enumName == null) {
            return false;
        }
        try {
            Enum.valueOf(enumClass, enumName);
            return true;
        } catch (final IllegalArgumentException ex) {
            return false;
        }
    }

    /**
     * <p>
     * Gets the enum for the class, returning {@code null} if not found.
     * </p>
     *
     * <p>
     * This method differs from {@link Enum#valueOf} in that it does not throw an exception for an
     * invalid enum name.
     * </p>
     *
     * @param <E>
     *            the type of the enumeration
     * @param enumClass
     *            the class of the enum to query, not null
     * @param enumName
     *            the enum name, null returns null
     * @return the enum, null if not found
     */
    public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) {
        if (enumName == null) {
            return null;
        }
        try {
            return Enum.valueOf(enumClass, enumName);
        } catch (final IllegalArgumentException ex) {
            return null;
        }
    }

    /**
     * <p>
     * Creates a long bit vector representation of the given subset of an Enum.
     * </p>
     *
     * <p>
     * This generates a value that is usable by {@link EnumUtils#processBitVector}.
     * </p>
     *
     * <p>
     * Do not use this method if you have more than 64 values in your Enum, as this would create a
     * value greater than a long can hold.
     * </p>
     *
     * @param enumClass
     *            the class of the enum we are working with, not {@code null}
     * @param values
     *            the values we want to convert, not {@code null}, neither containing {@code null}
     * @param <E>
     *            the type of the enumeration
     * @return a long whose value provides a binary representation of the given set of enum values.
     * @throws NullPointerException
     *             if {@code enumClass} or {@code values} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class or has more than 64 values, or if any
     *             {@code values} {@code null}
     * @since 3.0.1
     * @see #generateBitVectors(Class, Iterable)
     */
    public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass, final Iterable<E> values) {
        checkBitVectorable(enumClass);
        Validate.notNull(values);
        long total = 0;
        for (final E constant : values) {
            Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
            total |= 1 << constant.ordinal();
        }
        return total;
    }

    /**
     * <p>
     * Creates a bit vector representation of the given subset of an Enum using as many
     * {@code long}s as needed.
     * </p>
     *
     * <p>
     * This generates a value that is usable by {@link EnumUtils#processBitVectors}.
     * </p>
     *
     * <p>
     * Use this method if you have more than 64 values in your Enum.
     * </p>
     *
     * @param enumClass
     *            the class of the enum we are working with, not {@code null}
     * @param values
     *            the values we want to convert, not {@code null}, neither containing {@code null}
     * @param <E>
     *            the type of the enumeration
     * @return a long[] whose values provide a binary representation of the given set of enum values
     *         with least significant digits rightmost.
     * @throws NullPointerException
     *             if {@code enumClass} or {@code values} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class, or if any {@code values} {@code null}
     * @since 3.2
     */
    public static <E extends Enum<E>> long[] generateBitVectors(final Class<E> enumClass, final Iterable<E> values) {
        asEnum(enumClass);
        Validate.notNull(values);
        final EnumSet<E> condensed = EnumSet.noneOf(enumClass);
        for (final E constant : values) {
            Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
            condensed.add(constant);
        }
        final long[] result = new long[(enumClass.getEnumConstants().length - 1) / Long.SIZE + 1];
        for (final E value : condensed) {
            result[value.ordinal() / Long.SIZE] |= 1 << (value.ordinal() % Long.SIZE);
        }
        ArrayUtils.reverse(result);
        return result;
    }

    /**
     * <p>
     * Creates a long bit vector representation of the given array of Enum values.
     * </p>
     *
     * <p>
     * This generates a value that is usable by {@link EnumUtils#processBitVector}.
     * </p>
     *
     * <p>
     * Do not use this method if you have more than 64 values in your Enum, as this would create a
     * value greater than a long can hold.
     * </p>
     *
     * @param enumClass
     *            the class of the enum we are working with, not {@code null}
     * @param values
     *            the values we want to convert, not {@code null}
     * @param <E>
     *            the type of the enumeration
     * @return a long whose value provides a binary representation of the given set of enum values.
     * @throws NullPointerException
     *             if {@code enumClass} or {@code values} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class or has more than 64 values
     * @since 3.0.1
     * @see #generateBitVectors(Class, Iterable)
     */
    public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass, final E... values) {
        Validate.noNullElements(values);
        return generateBitVector(enumClass, Arrays.<E> asList(values));
    }

    /**
     * <p>
     * Creates a bit vector representation of the given subset of an Enum using as many
     * {@code long}s as needed.
     * </p>
     *
     * <p>
     * This generates a value that is usable by {@link EnumUtils#processBitVectors}.
     * </p>
     *
     * <p>
     * Use this method if you have more than 64 values in your Enum.
     * </p>
     *
     * @param enumClass
     *            the class of the enum we are working with, not {@code null}
     * @param values
     *            the values we want to convert, not {@code null}, neither containing {@code null}
     * @param <E>
     *            the type of the enumeration
     * @return a long[] whose values provide a binary representation of the given set of enum values
     *         with least significant digits rightmost.
     * @throws NullPointerException
     *             if {@code enumClass} or {@code values} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class, or if any {@code values} {@code null}
     * @since 3.2
     */
    public static <E extends Enum<E>> long[] generateBitVectors(final Class<E> enumClass, final E... values) {
        asEnum(enumClass);
        Validate.noNullElements(values);
        final EnumSet<E> condensed = EnumSet.noneOf(enumClass);
        Collections.addAll(condensed, values);
        final long[] result = new long[(enumClass.getEnumConstants().length - 1) / Long.SIZE + 1];
        for (final E value : condensed) {
            result[value.ordinal() / Long.SIZE] |= 1 << (value.ordinal() % Long.SIZE);
        }
        ArrayUtils.reverse(result);
        return result;
    }

    /**
     * <p>
     * Convert a long value created by {@link EnumUtils#generateBitVector} into the set of enum
     * values that it represents.
     * </p>
     *
     * <p>
     * If you store this value, beware any changes to the enum that would affect ordinal values.
     * </p>
     * 
     * @param enumClass
     *            the class of the enum we are working with, not {@code null}
     * @param value
     *            the long value representation of a set of enum values
     * @param <E>
     *            the type of the enumeration
     * @return a set of enum values
     * @throws NullPointerException
     *             if {@code enumClass} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class or has more than 64 values
     * @since 3.0.1
     */
    public static <E extends Enum<E>> EnumSet<E> processBitVector(final Class<E> enumClass, final long value) {
        checkBitVectorable(enumClass).getEnumConstants();
        return processBitVectors(enumClass, value);
    }

    /**
     * <p>
     * Convert a {@code long[]} created by {@link EnumUtils#generateBitVectors} into the set of enum
     * values that it represents.
     * </p>
     *
     * <p>
     * If you store this value, beware any changes to the enum that would affect ordinal values.
     * </p>
     * 
     * @param enumClass
     *            the class of the enum we are working with, not {@code null}
     * @param values
     *            the long[] bearing the representation of a set of enum values, least significant
     *            digits rightmost, not {@code null}
     * @param <E>
     *            the type of the enumeration
     * @return a set of enum values
     * @throws NullPointerException
     *             if {@code enumClass} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class
     * @since 3.2
     */
    public static <E extends Enum<E>> EnumSet<E> processBitVectors(final Class<E> enumClass, long... values) {
        final EnumSet<E> results = EnumSet.noneOf(asEnum(enumClass));
        values = ArrayUtils.clone(Validate.notNull(values));
        ArrayUtils.reverse(values);
        for (final E constant : enumClass.getEnumConstants()) {
            final int block = constant.ordinal() / Long.SIZE;
            if (block < values.length && (values[block] & 1 << (constant.ordinal() % Long.SIZE)) != 0) {
                results.add(constant);
            }
        }
        return results;
    }

    /**
     * Validate that {@code enumClass} is compatible with representation in a {@code long}.
     * 
     * @param <E>
     *            the type of the enumeration
     * @param enumClass
     *            to check
     * @return {@code enumClass}
     * @throws NullPointerException
     *             if {@code enumClass} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class or has more than 64 values
     * @since 3.0.1
     */
    private static <E extends Enum<E>> Class<E> checkBitVectorable(final Class<E> enumClass) {
        final E[] constants = asEnum(enumClass).getEnumConstants();
        Validate.isTrue(constants.length <= Long.SIZE, CANNOT_STORE_S_S_VALUES_IN_S_BITS, constants.length,
                enumClass.getSimpleName(), Long.SIZE);

        return enumClass;
    }

    /**
     * Validate {@code enumClass}.
     * 
     * @param <E>
     *            the type of the enumeration
     * @param enumClass
     *            to check
     * @return {@code enumClass}
     * @throws NullPointerException
     *             if {@code enumClass} is {@code null}
     * @throws IllegalArgumentException
     *             if {@code enumClass} is not an enum class
     * @since 3.2
     */
    private static <E extends Enum<E>> Class<E> asEnum(final Class<E> enumClass) {
        Validate.notNull(enumClass, ENUM_CLASS_MUST_BE_DEFINED);
        Validate.isTrue(enumClass.isEnum(), S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE, enumClass);
        return enumClass;
    }

    public static void main(String[] args) {
    }
}
